package it.unibo.refolding.pico.stripchart.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.util.List;

import javax.swing.JPanel;

public class ZtPanel extends JPanel {

	private static final long serialVersionUID = 7795352732341921448L;

	final JunctionPointsHolder h;
	private final short maxZ;

	public static final int halfSquareSide = 10;
  private final List<Color> colors;

	public ZtPanel(JunctionPointsHolder h, List<Color> colors) {
		this.h = h;
		short minZ = h.minZ();
		maxZ = h.maxZ();
		setPreferredSize(new Dimension(h.zLength(), maxZ - minZ + 1));
		this.colors = colors;
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Color savedColor = g.getColor();
		for (int i = 0; i <= h.modifiableJunctionPoints.size(); ++i) {
			final int from = i == 0 ? 0 : h.modifiableJunctionPoints.getInt(i - 1);
			final int to = i == h.modifiableJunctionPoints.size() ? h.zLength() - 1 : h.modifiableJunctionPoints.getInt(i);
			draw((Graphics2D) g, colors.get(i % colors.size()), from, to);
		}
		g.setColor(Color.BLACK);
		for (int i : h.modifiableJunctionPoints) {
			final int x = i - halfSquareSide;
			final int y = y(i) - halfSquareSide;
			final int side = 2 * halfSquareSide + 1;
			g.drawRect(x, y, side, side);
			g.drawLine(x, y, x + side, y + side);
			g.drawLine(x, y + side, x + side, y);
		}
		g.setColor(savedColor);
	}

	private void draw(Graphics2D g, Color color, int from, int to) {
		g.setColor(color);
		GeneralPath path = new GeneralPath();
		path.moveTo(from, y(from));
		for (int i = from + 1; i <= to; ++i) {
			path.lineTo(i, y(i));
		}
		g.draw(path);
	}

	public int y(int i) {
		return maxZ - h.z(i);
	}
}
